package code20_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test06_批处理 {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtil.getConnection();
			// 关闭自动提交事务
			conn.setAutoCommit(false);
			ps = conn.prepareStatement("insert into t_user values (null,?,?,?)");
			
			long start = System.currentTimeMillis();
			for(int i=1;i<=100500;i++){
				ps.setString(1, "name"+i);
				ps.setString(2, "123");
				ps.setInt(3, 18);
				// ps.executeUpdate();
				
				ps.addBatch(); // 添加批处理，放到缓冲区中
				
				// 设置批处理大小
				if(i%30000==0){
					ps.executeBatch(); // 批量执行，每10000条执行
					conn.commit();
				}
			}
			
			// 批量执行
			ps.executeBatch();
			conn.commit();
			
			long end = System.currentTimeMillis();
			System.out.println("花费的时间："+(end-start));
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			JdbcUtil.close(conn, ps, null);
		}
	}
}
